package com.zhongshengnetwork.rightbe.wzt.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.wang.avi.AVLoadingIndicatorView;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.ScreenUtils;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.customview.CustomDialog;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.WeiShuContentDetailModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.login.LoginActivity;
import com.zhongshengnetwork.rightbe.wzt.view.WZTRecyclerAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static android.widget.AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL;
import static android.widget.NumberPicker.OnScrollListener.SCROLL_STATE_FLING;

public class WZTContentSearchActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener {

    private TopBarView topbar;
    private long id;
    private String wztUserId = "";
    private Byte contentType = 0;
    private boolean canBrowseAll = false;
    private boolean needCare = false;
    private boolean careState = false;
    private boolean canPublish = false;

    private int pageindex = 0;
    private static final int Records = 20;
    private static final int maxReadCount = 10;
    //private String lastDay = "";
    private boolean isHasMore = false;
    private List<WeiShuContentDetailModel> list;
    private RecyclerView listview;
    private WZTRecyclerAdapter wztRecyclerAdapter;
    private int imgW = 0;

    //加载动画
    private AVLoadingIndicatorView avi;
    private RefreshLayout mRefreshLayout;
    //private NestedScrollView wzt_nestedScrollView_layout;

    private ImageView no_data_img;
    private TextView wzt_load_all;

    private int screenWidth = 0;
    private float density = 0;


    private String dataContent = "";
    private EditText search_edit;
    private Button search_button;

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        finish();
        //Toast.makeText(LangDetailActivity.this, "你点击了左侧按钮", Toast.LENGTH_LONG).show();

    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    public void hintKeyBoard() {
        //拿到InputMethodManager
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //如果window上view获取焦点 && view不为空
        if (imm.isActive() && getCurrentFocus() != null) {
            //拿到view的token 不为空
            if (getCurrentFocus().getWindowToken() != null) {
                //表示软键盘窗口总是隐藏，除非开始时以SHOW_FORCED显示。
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    private void onClickSearch(View view){
        hintKeyBoard();
        String text = search_edit.getText().toString();
        dataContent = text;
        if (mRefreshLayout != null){
            Log.e("TAG","进来获取数据了刷新界面");
                /*
                @param delayed 开始延时
                @param duration 拖拽动画持续时间
                @param dragRate 拉拽的高度比率（要求 ≥ 1 ）
                */
            mRefreshLayout.autoRefresh(100,300,1f,false);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        calculateImageWidth();
    }

    private void calculateImageWidth(){
        screenWidth = ScreenUtils.getScreenWidth(WZTContentSearchActivity.this);
        density = ScreenUtils.getScreenDensity(WZTContentSearchActivity.this);
        if (contentType == 2){
            imgW = (int) ((screenWidth-130*density)/3);
        }else {
            imgW = (int) ((screenWidth-30*density)/3);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wztcontent_search);

        calculateImageWidth();

        id = getIntent().getLongExtra("id", 0);
        wztUserId = getIntent().getStringExtra("userid");
        contentType = getIntent().getByteExtra("contentType", Byte.valueOf("0"));
        canBrowseAll = getIntent().getBooleanExtra("canBrowseAll", true);
        needCare = getIntent().getBooleanExtra("needCare", false);
        careState = getIntent().getBooleanExtra("careState", false);
        canPublish = getIntent().getBooleanExtra("canPublish", false);
        String title = getIntent().getStringExtra("title");

        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.setClickListener(this);
        topbar.getTitleView().setText(title);

        no_data_img = (ImageView) findViewById(R.id.no_data_img);
        wzt_load_all = (TextView) findViewById(R.id.wzt_load_all);
        wzt_load_all.setClickable(true);
        wzt_load_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hintKeyBoard();
                showCare();
            }
        });

        search_edit = (EditText) findViewById(R.id.search_edit);
        search_edit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH) {
                    String search = search_edit.getText().toString().trim();
                    onClickSearch(textView);
                    return true;
                }
                return false;
            }
        });
        search_button = (Button) findViewById(R.id.search_button);
        search_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickSearch(v);
            }
        });
        search_edit.setHintTextColor(AppThemeUtils.getInstance().getLightTextColor());
        search_edit.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        RelativeLayout search_top = (RelativeLayout) findViewById(R.id.search_top);
        search_top.setBackgroundColor(AppThemeUtils.getInstance().getSearchBgColor());
        RelativeLayout search_shape_layout = (RelativeLayout) findViewById(R.id.search_shape_layout);
        search_shape_layout.setBackgroundResource(AppThemeUtils.getInstance().getSearchBackground());

        pageindex = 0;
        if (list == null){
            list = new ArrayList<WeiShuContentDetailModel>();
        }

        listview=(RecyclerView) findViewById(R.id.wzt_listview);
        LinearLayoutManager layoutManager = new LinearLayoutManager(WZTContentSearchActivity.this);
        listview.setLayoutManager(layoutManager);
        listview.setHasFixedSize(false);
        listview.setNestedScrollingEnabled(false);
        ((DefaultItemAnimator) listview.getItemAnimator()).setSupportsChangeAnimations(false);//解决局部更新闪烁问题
        wztRecyclerAdapter = new WZTRecyclerAdapter(list, WZTContentSearchActivity.this, listview, contentType, canBrowseAll, wztUserId, id);
        listview.setAdapter(wztRecyclerAdapter);

        mRefreshLayout = (RefreshLayout) findViewById(R.id.refreshLayout);
        //设置 Header 为 贝塞尔雷达 样式
        mRefreshLayout.setRefreshHeader(new BezierRadarHeader(WZTContentSearchActivity.this).setEnableHorizontalDrag(true));//BezierRadarHeader
        //设置 Footer 为 球脉冲 样式
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(WZTContentSearchActivity.this).setSpinnerStyle(SpinnerStyle.FixedBehind));//BallPulseFooter ClassicsFooter
        mRefreshLayout.setPrimaryColors(AppThemeUtils.getInstance().getRefreshBackgroundColor(),AppThemeUtils.getInstance().getRefreshAccessColor());
        mRefreshLayout.setEnableRefresh(true);
        mRefreshLayout.setEnableLoadMore(false);
        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                getData(false);
            }
        });
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                //refreshlayout.finishRefresh();
                getData(true);
            }
        });

        RelativeLayout wzt_content_layout = (RelativeLayout) findViewById(R.id.wzt_layout);
        wzt_content_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
        listview.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
        listview.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == SCROLL_STATE_FLING ||
                        newState == SCROLL_STATE_TOUCH_SCROLL){
                    hintKeyBoard();
                }
            }
        });

        mRefreshLayout.autoRefresh();

    }

    private void showCare(){
        CustomDialog dialog = null;
        final CustomDialog.Builder builder = new CustomDialog.Builder(WZTContentSearchActivity.this);
        builder.setTitle("温馨提示");
        builder.setMessage("关注作者后才可以查看全部内容，是否现在添加关注？");
        builder.setPositiveButton("关注", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                addCare();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog = builder.create();
        dialog.show();
    }

    private void addCare(){
        if (CommonUtils.isLogin() == false){
            Intent intent = new Intent(WZTContentSearchActivity.this, LoginActivity.class);
            startActivity(intent);
            return;
        }
        if (careState == false){
            if (wztUserId.equals(CustomApplication.loginModel.getUid())){
                canBrowseAll = true;
                careState = true;
                wzt_load_all.setVisibility(View.GONE);
                wztRecyclerAdapter.canBrowseAll = true;
                wztRecyclerAdapter.notifyDataSetChanged();
                return;
            }
            final HashMap<String, String> map = new HashMap<String, String>();
            map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
            map.put("authorid", wztUserId);
            String url = "miniapp/"+"langappid"+"/addcare.do";
            HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                @Override
                public void onSuccess(String data) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            CommonModel commonModel = GsonTools.getCommonModel(data);
                            if (commonModel.getFlag().equals("1")){
                                ToastUtil.show(WZTContentSearchActivity.this, "关注成功");
                                canBrowseAll = true;
                                careState = true;
                                wzt_load_all.setVisibility(View.GONE);
                                wztRecyclerAdapter.canBrowseAll = true;
                                wztRecyclerAdapter.notifyDataSetChanged();
                            }else {
                                ToastUtil.show(WZTContentSearchActivity.this, commonModel.getMsg());
                            }
                        }
                    });
                }

                @Override
                public void onError(String msg) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.show(WZTContentSearchActivity.this, "添加关注失败");
                        }
                    });
                }
            });
        }else {
            canBrowseAll = true;
            careState = true;
            wzt_load_all.setVisibility(View.GONE);
            wztRecyclerAdapter.canBrowseAll = true;
            wztRecyclerAdapter.notifyDataSetChanged();
        }
    }

    public void getData(boolean isFirst){

        if (isFirst == true){
            pageindex = 0;
        }

        if (list != null && list.size() > maxReadCount && canBrowseAll == false){
            mRefreshLayout.finishLoadMore();
            showCare();
            return;
        }else {
            if (wzt_load_all.getVisibility() == View.VISIBLE){
                wzt_load_all.setVisibility(View.GONE);
            }
        }

        hintKeyBoard();
        if (search_edit != null){
            if (search_edit.getText() != null){
                String text = search_edit.getText().toString();
                dataContent = text;
            }else {
                dataContent = "";
            }
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                final HashMap<String, String> map = new HashMap<String, String>();
                map.put(APIKey.tokenKey, CommonUtils.formatString(CustomApplication.loginModel.getToken()));
                map.put("dataId",""+id);
                map.put("dataType", "0");
                map.put("pageIndex",pageindex+"");
                map.put("pageRecord",Records+"");
                map.put("dataContent", CommonUtils.formatString(dataContent));
                HttpsUtils.miniAppDo(map, "weishu/theme/list.do", new HttpCallBack() {
                    @Override
                    public void onSuccess(String data) {
                        final CommonModel commonModel = GsonTools.getCommonModel(data);
                        if (commonModel.getFlag().equals("1")){
                            final List<WeiShuContentDetailModel> l = GsonTools.getWeiShuContentDetailModelList(data);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (mRefreshLayout.getState() == RefreshState.Loading){
                                        //listview.stopLoadMore();
                                        mRefreshLayout.finishLoadMore();
                                    }else {
                                        list.clear();
                                        //listview.stopRefresh(true);
                                        mRefreshLayout.finishRefresh();
                                    }
                                    int fromposition = list.size();
                                    if (l != null && l.size() > 0){
                                        if (l.size() >= Records){
                                            mRefreshLayout.setEnableLoadMore(true);
                                        }else {
                                            mRefreshLayout.setEnableLoadMore(false);
                                        }
                                        if (pageindex == 0){
                                            list.clear();
                                        }
                                        list.addAll(l);
                                        no_data_img.setVisibility(View.GONE);
                                    }else {
                                        if (pageindex == 0){
                                            no_data_img.setVisibility(View.VISIBLE);
                                        }
                                        isHasMore = false;
                                        mRefreshLayout.setEnableLoadMore(false);
                                    }
                                    if (pageindex == 0){
                                        wztRecyclerAdapter.notifyDataSetChanged();
                                    }else {
                                        wztRecyclerAdapter.notifyItemRangeChanged(fromposition, l.size());
                                    }
                                    if (l != null && l.size() > 0){
                                        pageindex += 1;
                                    }
                                    if (list != null && list.size() > maxReadCount && canBrowseAll == false){
                                        if (wzt_load_all.getVisibility() == View.GONE){
                                            wzt_load_all.setVisibility(View.VISIBLE);
                                        }
                                    }

                                }
                            });
                        }else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mRefreshLayout.finishLoadMore();
                                    CustomApplication.showTip(commonModel, WZTContentSearchActivity.this);
                                }
                            });
                        }
                    }

                    @Override
                    public void onError(String msg) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mRefreshLayout.finishLoadMore();
                            }
                        });
                    }
                });
            }
        }).start();

    }

}
